﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

using Seven.Tools.Helper;

namespace Seven.Site.Mvc
{
    public class TrimModelBinder : DefaultModelBinder
    {
        /// <summary>
        /// 重写SetProperty 自动去除前后空格 
        /// 可以直接在global中注册 ModelBinders.Binders.DefaultBinder = new Models.TrimModelBinder();
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="bindingContext"></param>
        /// <param name="propertyDescriptor"></param>
        /// <param name="value"></param>
        protected override void SetProperty(ControllerContext controllerContext,
            ModelBindingContext bindingContext,
            System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
        {
            object temp = value;
            if (propertyDescriptor.PropertyType == typeof(string))
            {
                var stringValue = (string)value;
                if (!string.IsNullOrEmpty(stringValue))
                { stringValue = stringValue.Trim(); }
                temp = stringValue;
            }

            base.SetProperty(controllerContext, bindingContext, propertyDescriptor, temp);
        }
    }

    /// <summary>
    /// Json数据绑定类 对json数据反序列化，使其支持对象集合参数
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class JsonBinder<T> : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            //从请求中获取提交的参数数据 
            var json = controllerContext.HttpContext.Request.Form[bindingContext.ModelName] as string;
            //提交参数是对象 
            if (json.StartsWith("{") && json.EndsWith("}"))
            {
                return JsonHelper.DeserializeJsToObject(json, typeof(T));
            }
            //提交参数是数组 
            if (json.StartsWith("[") && json.EndsWith("]"))
            {
                return JsonHelper.DeserializeJsToArray<T>(json);
            }
            return null;
        }
    }
}
